<template>
	<up-popup :show="show" @close="close" closeable>
		<view class="list-box p-10">
			<view style="width:90%;" class="m-b-10">
				<up-input style="height: 32rpx;" :placeholder="placeholder" v-model="searchVal" class="bg-color"
					clearable @change="handleChange">
				</up-input>
			</view>
			<up-list @scrolltolower="scrolltolower" :height="height" width="100%" v-if="newList.length>0">
				<up-list-item v-for="(item, index) in newList" :key="index">
					<slot name="list" :row="item"></slot>
				</up-list-item>
			</up-list>
			<up-empty :style="{height:height+'px'}" v-else mode="list"></up-empty>
		</view>
	</up-popup>
</template>

<script setup>
	const props = defineProps({
		//弹框状态
		show: {
			type: Boolean,
			default: false,
		},
		//请求的数据的函数
		dataFn: {
			type: Function,
			default: null,
			required: true
		},
		//搜索框的placeholder
		placeholder: {
			type: String,
			default: '请输入',
		},
		//list和empty的高度
		height: {
			type: [String, Number],
			default: '400',
		},
		//搜索框的查询参数
		query: {
			type: Array,
			default: () => []
		},
		//搜索默认参数
		defaultParams: {
			type: Object,
			default: () => ({})
		},
		// 是否需要分页
		paging: {
			type: Boolean,
			default: true
		}
	});

	const emits = defineEmits(['close'])

	const searchVal = ref('') //搜索值
	let list = []
	const newList = ref([])
	const total = ref(0)
	let queryObj = ref({})
	const queryParams = reactive({
		needCount: 1,
		pageNum: 1,
		pageSize: 20,
	})

	async function getData() {
		try {
			if (!props.dataFn) return
			let params = {}

			params = props.paging ? {
				...props.defaultParams,
				...queryObj.value,
				...queryParams
			} : props.defaultParams

			const {
				data
			} = await props.dataFn(params)

			list = props.paging ? [...list, ...data.rows || []] : data || []

			total.value = data.total || 0
			newList.value = list
		} catch (e) {
			console.error(e)
		}
	}

	const fangdou = debounce(getData, 800);

	// 搜索框change
	const handleChange = () => {
		if (props.paging) {
			queryParams.pageNum = 1
			props.query.forEach((item, index) => {
				queryObj.value[item] = searchVal.value
			})
			list = []
			fangdou()
		} else {
			newList.value = list.filter((item) => {
				return props.query.some((inm) => item[inm].includes(searchVal.value))
			})
		}
	}
	// 关闭弹框
	function close() {
		emits('close')
	}
	// 触底事件
	function scrolltolower() {
		if (queryParams.pageNum * queryParams.pageSize < total.value) {
			queryParams.pageNum++
			getData()
		}
	}

	watch(() => props.show, (newValue) => {
		if (newValue) {
			list = []
			searchVal.value = ""
			queryObj.value = {}
			getData()
		}
	})
</script>

<style scoped lang="scss">
	.list-box {
		background-color: #f3f4f6;
	}
</style>